<template>
    <PlayGround v-if="$store.state.pk.status==='playing'"/>

    <MatchGround v-if="$store.state.pk.status==='matching'"/>
    <OverGround v-if="$store.state.pk.loser != 'none'" />
</template>

<script>
import PlayGround from '@/components/PlayGround.vue';
import MatchGround from "@/components/MatchGround.vue";
import {useStore} from "vuex";
import {onMounted, onUnmounted} from "vue";
import OverGround from "@/components/OverGround.vue";

export default {
    name: "pkIndex",
    components: {
        PlayGround,
        MatchGround,
        OverGround,
    },
    setup() {
        const store = useStore();
        const socketUrl = `ws://localhost:3000/websocket/${store.state.user.token}`;
        let socket = null;
        onMounted(() => {
            socket = new WebSocket(socketUrl);
            socket.onopen = () => {//连接成功时调用的函数
                console.log("connected!");
                store.commit("updateSocket", socket);
            }

            socket.onmessage = (msg) => {//前端接收到信息时调用的函数
                const data = JSON.parse(msg.data);
                if (data.event === "match-success") {  // 匹配成功
                    store.commit("updateOpponent", {
                        username: data.opponent_username,
                        photo: data.opponent_photo,
                    });
                    setTimeout(() => {
                        store.commit("updateStatus", "playing");
                    }, 200);
                    store.commit("updateGame", data.game);

                }
                if (data.event === "result") {
                    console.log(data);
                    const game = store.state.pk.gameObject;
                    const [snake0, snake1] = game.snakes;
                    if (data.loser === "all" || data.loser === "A") {
                        snake0.status = "die";
                    }
                    if (data.loser === "all" || data.loser === "B") {
                        snake1.status = "die";
                    }
                    store.commit("updateLoser",data.loser);
                }

                if (data.event === "move") {
                    const game = store.state.pk.gameObject;
                    const [snake0, snake1] = game.snakes;
                    snake0.set_direction(data.a_direction);
                    snake1.set_direction(data.b_direction);
                }


            }

            socket.onclose = () => {
                console.log("close");
                store.commit("updateStatus", "matching");
                store.commit("updateOpponent",{
                    username:"???",
                    photo:"https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png",
                })
            }
        })

        onUnmounted(() => {
            store.commit("updateLoser","none");
            socket.close();
        })
    }

};
</script>

<style></style>
